import { Injectable, NotFoundException, ForbiddenException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { GalleryImage } from './entities/gallery-image.entity';
import { User } from '../common/entities/user.entity';
import { GalleryQueryDto } from './dto/gallery-query.dto';
import { UpdateGalleryImageDto } from './dto/update-gallery-image.dto';
const sizeOf = require('image-size');
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class GalleryService {
  constructor(
    @InjectRepository(GalleryImage)
    private galleryImageRepository: Repository<GalleryImage>,
  ) {}

  async findAll(query: GalleryQueryDto, userId: number) {
    const { page = 1, pageSize = 20, keyword } = query;
    const skip = (page - 1) * pageSize;

    const queryBuilder = this.galleryImageRepository
      .createQueryBuilder('image')
      .where('image.userId = :userId', { userId })
      .orderBy('image.uploadTime', 'DESC');

    if (keyword) {
      queryBuilder.andWhere(
        '(image.name LIKE :keyword OR image.description LIKE :keyword)',
        { keyword: `%${keyword}%` }
      );
    }

    const [list, total] = await queryBuilder
      .skip(skip)
      .take(pageSize)
      .getManyAndCount();

    const totalPages = Math.ceil(total / pageSize);

    // 列表返回缩略图，但保持原图URL不变
    const listWithThumbnails = list.map(image => {
      // 保持原图URL不变，缩略图URL在thumbnail字段中
      return {
        ...image,
        // url字段保持原图地址，thumbnail字段是缩略图地址
        // 前端可以根据需要选择使用url或thumbnail
      };
    });

    return {
      list: listWithThumbnails,
      pagination: {
        page,
        pageSize,
        total,
        totalPages,
        hasMore: page < totalPages,
      },
    };
  }

  async findOne(id: number, userId: number): Promise<GalleryImage> {
    const image = await this.galleryImageRepository.findOne({
      where: { id, userId },
    });

    if (!image) {
      throw new NotFoundException('图片不存在');
    }

    // 详情返回原图（保持原始URL）
    return image;
  }

  async create(file: Express.Multer.File, name: string, description: string, userId: number): Promise<GalleryImage> {
    // 验证文件类型
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    if (!allowedTypes.includes(file.mimetype)) {
      throw new BadRequestException('文件格式不支持');
    }

    // 验证文件大小 (10MB)
    const maxSize = 10 * 1024 * 1024;
    if (file.size > maxSize) {
      throw new BadRequestException('文件大小超限');
    }

    try {
      console.log('开始处理图片:', file.filename, file.mimetype, file.size);
      
      // 生成文件URL
      const baseUrl = process.env.BASE_URL || 'http://localhost:3000';
      const url = `${baseUrl}/uploads/${file.filename}`;
      
      // 创建缩略图目录
      const thumbnailDir = './uploads/thumbnails';
      if (!fs.existsSync(thumbnailDir)) {
        fs.mkdirSync(thumbnailDir, { recursive: true });
        console.log('创建缩略图目录:', thumbnailDir);
      }

      // 生成缩略图
      const thumbnailFilename = `thumb_${file.filename}`;
      const thumbnailPath = path.join(thumbnailDir, thumbnailFilename);
      const thumbnailUrl = `${baseUrl}/uploads/thumbnails/${thumbnailFilename}`;

      console.log('开始处理图片...');
      
      // 获取图片尺寸
      let width = 1920;
      let height = 1080;
      
      try {
        // 使用image-size获取图片尺寸
        const dimensions = sizeOf(file.buffer);
        width = dimensions.width || 1920;
        height = dimensions.height || 1080;
        console.log('图片尺寸:', width, 'x', height);
      } catch (sizeError) {
        console.warn('获取图片尺寸失败，使用默认尺寸:', sizeError.message);
      }
      
      // 计算缩略图尺寸（最大宽度300px）
      const maxWidth = 300;
      let thumbnailWidth = width;
      let thumbnailHeight = height;
      
      if (width > maxWidth) {
        thumbnailWidth = maxWidth;
        thumbnailHeight = Math.round((height * maxWidth) / width);
      }

      console.log('缩略图尺寸:', thumbnailWidth, 'x', thumbnailHeight);

      // 使用sips命令生成缩略图
      try {
        const { exec } = require('child_process');
        const util = require('util');
        const execAsync = util.promisify(exec);
        
        // 使用sips命令生成缩略图
        const sipsCommand = `sips -z ${thumbnailHeight} ${thumbnailWidth} "${file.path}" --out "${thumbnailPath}"`;
        console.log('执行sips命令:', sipsCommand);
        
        await execAsync(sipsCommand);
        console.log('缩略图已保存:', thumbnailPath);
      } catch (sipsError) {
        console.warn('sips处理失败，复制原图作为缩略图:', sipsError.message);
        // 如果sips失败，复制原图作为缩略图
        try {
          fs.copyFileSync(file.path, thumbnailPath);
          console.log('缩略图已保存（复制原图）:', thumbnailPath);
        } catch (copyError) {
          console.warn('复制缩略图失败:', copyError.message);
          // 如果复制失败，创建一个占位符文件
          fs.writeFileSync(thumbnailPath, file.buffer);
        }
      }

      // 创建数据库记录
      const galleryImage = this.galleryImageRepository.create({
        userId,
        name,
        url,
        thumbnail: thumbnailUrl,
        size: file.size,
        width,
        height,
        format: file.mimetype.split('/')[1],
        description,
      });

      const savedImage = await this.galleryImageRepository.save(galleryImage);
      console.log('图片记录已保存:', savedImage.id);
      return savedImage;
    } catch (error) {
      console.error('图片处理错误:', error);
      console.error('错误堆栈:', error.stack);
      throw new BadRequestException(`图片处理失败: ${error.message}`);
    }
  }

  async update(id: number, updateDto: UpdateGalleryImageDto, userId: number): Promise<GalleryImage> {
    const image = await this.findOne(id, userId);
    
    Object.assign(image, updateDto);
    return await this.galleryImageRepository.save(image);
  }

  async remove(id: number, userId: number): Promise<void> {
    const image = await this.findOne(id, userId);
    await this.galleryImageRepository.remove(image);
  }
}
